/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package br.jm.mala.lazyModel;

import br.jm.mala.service.GenericService;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.primefaces.model.LazyDataModel;
import org.primefaces.model.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;

public final class GenericLazyDataModel<T extends Serializable> extends LazyDataModel<T> {

    private static final long serialVersionUID = 8322155218114748177L;

    private GenericService<T> service;
    boolean lSorter;
    private int dataSize = 0;
    private String cParametroSQL = "";
    private String cFiltro = "";
    private final String cTabela;

    @Autowired
    public GenericLazyDataModel(GenericService<T> service, String cParametroSQL, String cFiltro, String cTabela) {
        this.service = service;
        this.cParametroSQL = cParametroSQL;
        this.cFiltro = cFiltro;
        this.cTabela = cTabela;
        this.dataSize = getRowCount();
    }

    public GenericService<T> getService() {
        return service;
    }

    public void setService(GenericService<T> service) {
        this.service = service;
    }

    @Override
    public final int getRowCount() {
        return service.getCount(cTabela);
    }

    @Override
    public List<T> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map filters) {
        List<T> data = new ArrayList<>();

        lSorter = SortOrder.ASCENDING.equals(sortOrder);

        data = service.getNative(cTabela, first, pageSize, sortField, lSorter, filters, cParametroSQL, cFiltro);

        //rowCount
        if (filters != null) {
            this.setRowCount(data.size());
        } else {
            this.setRowCount(dataSize);
        }
        return data;
    }

    @Override
    public Object getRowKey(T m) {
        return m.getClass();
    }

    @Override
    public T getRowData(String rowKey) {
        return service.getPorId(Long.parseLong(rowKey));
    }
}
